/*
 * @version: 1.0.0
 * @Author: fl
 * @Date: 2020-07-06 11:50:33
 * @LastEditTime: 2020-09-08 17:54:24
 */
import { defaultHandler } from '@/utils/request';
import { createAddress, deleteAddress, queryAddressItem, queryAddressList, updateAddress } from '@/api/address';
import Paging from '@/utils/paging';

const initialPaging = Paging.initialValue();

export default {
  namespaced: true,
  state: {
    list: [], //表示的所有地址的列表
    profile: {}, //表示的某个地址的信息
    paging: initialPaging,
  },
  mutations: {
    saveList(state, data) {
      const { list = [] } = data;
      console.log(list, '<这是list>');
      state.list = list;
    },
    saveProfile(state, data) {
      console.log(data, '<-这是获取地址信息data->');
      const { address = {} } = data || {};
      console.log(address, '<这是-address->');
      state.profile = address;
    },
    resetList(state) {
      state.list = [];
    },
    resetProfile(state) {
      state.profile = {};
    },
    afterSave(state, data) {
      console.log(data, '这是保存的data');
      const { list = [] } = data;
      state.list = list;
      console.log('我执行了');
      const profile = list.find(val => val.id === profile.id);
      state.profile = { ...state.profile, ...profile };
    },
    setisDefault(state) {
      if (typeof state.profile.isDefault == 'undefined') {
        state.profile.isDefault = false;
      }
    },
    updateProfile(state, data) {
      console.log({ ...data }, '<这是输入框篡改过-data->');

      state.profile = { ...state.profile, ...data };
      // state.profile = { ...state.profile, ...data };
    },
    updateListItem(state, data) {
      state.list = state.list.map(val => (val.id === data.id ? { ...val, ...data } : val));
    },
    updateDefaultAd(state) {
      console.log('我再切换');
      state.profile.isDefault = !state.profile.isDefault; //点击复选框,取反切换状态
    },
    deleteListItem(state, data) {
      state.list = state.list.filter(val => val.id !== data.id);
    },
  },
  actions: {
    fetch({ commit }, params = {}) {
      return queryAddressList(params)
        .then(data => commit('saveList', data))
        .catch(defaultHandler);
    },
    view({ commit }, params = {}) {
      return queryAddressItem(params)
        .then(data => commit('saveProfile', data))
        .catch(defaultHandler);
    },
    add({ commit }, params = {}) {
      return createAddress(params)
        .then(data => commit('afterSave', data))
        .catch(defaultHandler);
    },
    update({ commit }, params = {}) {
      return updateAddress(params)
        .then(data => commit('afterSave', data))
        .catch(defaultHandler);
    },
    remove({ commit }, params = {}) {
      return deleteAddress(params)
        .then(data => commit('deleteListItem', data))
        .catch(defaultHandler);
    },
  },
};
